# app/main.py
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware

from app.exceptions.handlers import http_exception_handler, global_exception_handler, validation_exception_handler
from contextlib import asynccontextmanager

from app.config.base_setting import backend_logger
from app.routes import ocr, excel, download, about, upload, progress, log_receiver
from app.config.base_setting import ALLOWED_ORIGINS

from app.jobs.cleanup_job import run_daily_archive_and_cleanup
import threading
import time

@asynccontextmanager
async def lifespan(app: FastAPI):
    backend_logger.info("Backend started and logger is working.")

    # 启动定时清理线程
    def cleanup_loop():
        while True:
            run_daily_archive_and_cleanup()
            time.sleep(3600 * 6)  # 每 6 小时运行一次

    thread = threading.Thread(target=cleanup_loop, daemon=True)
    thread.start()

    yield  # 应用在此处运行

    backend_logger.info("🔚 Backend shutting down.")


app = FastAPI(title="Zennotac Backend", lifespan=lifespan)

# 允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include all API routes
app.include_router(ocr.router, prefix="/api", tags=["Ocr"])
app.include_router(upload.router, prefix="/api", tags=["Upload"])
app.include_router(excel.router, prefix="/api", tags=["Excel"])
app.include_router(download.router, prefix="/api", tags=["Download"])
app.include_router(about.router, prefix="/api", tags=["About"])
app.include_router(log_receiver.router, prefix="/api", tags=["Log"])
app.include_router(progress.router, prefix="/api", tags=["Progress"])

# Register custom exception handlers
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, global_exception_handler)

@app.get("/")
def root():
    return {"message": "Welcome to Zennotac OCR Parser!"}

@app.get("/api/health", tags=["Health"])
async def health_check():
    return {"status": "ok", "message": "Zennotac backend is running"}
